//
//  ProblemClassViewController.m
//  Uhomebk
//
//  Created by Chiang on 2017/10/19.
//  Copyright © 2017年 mac. All rights reserved.
//

#import "ProblemClassViewController.h"
#import "ProblemClassCell.h"
#import "ProblemModel.h"

#define kCellIdentifier @"kCellIdentifier"

@interface ProblemClassViewController ()<UITableViewDelegate,UITableViewDataSource> {
    UITableView *tableView1;//根节点列表
    UITableView *tableView2;//子节点列表
    UITableView *tableView3;//叶子节点列表
    NSMutableArray *rootArr;
    NSMutableArray *childArr;
    NSMutableArray *leafArr;
    UIView *lineView2;
    UIView *lineView3;
}

@end

@implementation ProblemClassViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self initData];

    [self newSubmitButton];
    tableView1 = [self newTableViewWithFrame:CGRectZero];
    tableView2 = [self newTableViewWithFrame:CGRectZero];
    tableView3 = [self newTableViewWithFrame:CGRectZero];

    [self.view addSubview:tableView1];
    [self.view addSubview:tableView2];
    [self.view addSubview:tableView3];
    [tableView1 reloadData];
    [tableView2 reloadData];
    [tableView3 reloadData];

    lineView2 = [self newLine];
    lineView3 = [self newLine];
    [self.view addSubview:lineView2];
    [tableView3 addSubview:lineView3];
    [self seg_updateViewConstraints];
}

/**
 数据初始化
 */
- (void)initData {
    rootArr = [NSMutableArray array];
    childArr = [NSMutableArray array];
    leafArr = [NSMutableArray array];
    [rootArr addObjectsFromArray:[self getRootArray:_dataArray]];
    if (rootArr.count == 0) {
        return;
    }
    NSDictionary *defaultDic = rootArr[0];
    if ([self readSelectedStatus] == nil) {//没有选择过的数据，默认选择第一类的第一个
        [childArr addObjectsFromArray:[self getChildArrayWithId:rootArr[0][@"issueCategoryId"] dataArray:_dataArray]];
        [defaultDic setValue:@"1" forKey:@"status"];//选中状态，用于背景色判断
        if (childArr.count == 0) {
            [self setSelectedStatus:defaultDic];
        }
    } else {//选择过的数据，需要解析出来展示
        NSDictionary *selectDic = [self getSelectedCategoryDic];
        if ([[SEGUtils ValueToString:selectDic[@"parIssueCategoryId"]] isEqualToString:@"-1"]) {//一层
            
        } else {
            NSDictionary *fatherDic = [self getFatherSelectDic:selectDic[@"parIssueCategoryId"]];
            NSDictionary *rootSelectDic = [self getRootSelectDic:selectDic[@"parIssueCategoryId"]];
            [childArr addObjectsFromArray:[self getChildArrayWithId:rootSelectDic[@"issueCategoryId"] dataArray:_dataArray]];
            if ([[SEGUtils ValueToString:fatherDic[@"parIssueCategoryId"]] isEqualToString:@"-1"]) {//两层
            } else {//三层
                [leafArr addObjectsFromArray:[self getChildArrayWithId:fatherDic[@"issueCategoryId"] dataArray:_dataArray]];
            }
        }
    }
}


/**
 不同tableView切换数据源
 */
- (NSArray *)dataArrayInTableView:(UITableView *)tableView {
    if (tableView == tableView1) {
        return rootArr;
    } else if (tableView == tableView2) {
        return childArr;
    } else if (tableView == tableView3) {
        return leafArr;
    }
    return nil;
}

#pragma mark - UITableViewDataSource

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [[self dataArrayInTableView:tableView] count];
}

-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    ProblemClassCell *cell = [tableView dequeueReusableCellWithIdentifier:kCellIdentifier forIndexPath:indexPath];
    cell.selectDic = [self dataArrayInTableView:tableView][indexPath.row];
    return cell;
}

#pragma mark - UITableViewDelegate

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 44;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    NSArray * arr = [self dataArrayInTableView:tableView];
    [self clearAllStatus:arr];
    NSDictionary *seletDic = arr[indexPath.row];
    for (NSDictionary *dic in arr) {
        if (seletDic == dic) {
            [self setSelectedStatus:dic];
            [dic setValue:@"1" forKey:@"status"];//选中状态，用于背景色判断

        } else {
            [self setUnSelectedStatus:dic];
            [dic setValue:@"0" forKey:@"status"];
        }
    }
    [tableView reloadData];
    
    //点击上层刷新下层数据
    if (tableView == tableView1) {
        NSArray *arr = [self getChildArrayWithId:seletDic[@"issueCategoryId"] dataArray:_dataArray];
        [self clearAllStatus:arr];

        [childArr removeAllObjects];
        [leafArr removeAllObjects];
        if (arr.count > 0) {
            [self setUnSelectedStatus:seletDic];
            [childArr addObjectsFromArray:arr];
        }
        [tableView2 reloadData];
        [tableView3 reloadData];

    } else if (tableView == tableView2) {
        NSArray *arr = [self getChildArrayWithId:seletDic[@"issueCategoryId"] dataArray:_dataArray];
        [self clearAllStatus:arr];
        [leafArr removeAllObjects];
        if (arr.count > 0) {
            [self setUnSelectedStatus:seletDic];
            [leafArr addObjectsFromArray:arr];
        }
        [tableView3 reloadData];
    }
    [self seg_updateViewConstraints];
}

#pragma mark - Methods
/**
 设置为选中状态，选择的数据
 */
- (void)setSelectedStatus:(NSDictionary *)dic {
    [dic setValue:@"1" forKey:@"sel"];

}

/**
 设置为未选中状态，选择的数据
 */
- (void)setUnSelectedStatus:(NSDictionary *)dic {
    [dic setValue:@"0" forKey:@"sel"];
}

/**
 清除所有状态
 */
- (void)clearAllStatus:(NSArray *)arr {
    for (NSDictionary *dic in arr) {
        [dic setValue:@"0" forKey:@"sel"];
        [dic setValue:@"0" forKey:@"status"];//选中状态，用于背景色判断
    }
}
/**
 获取根节点
 @param dataArray 数据源数组
 */
- (NSArray *)getRootArray:(NSArray *)dataArray {
    NSMutableArray *rootArray = [NSMutableArray array];
    for (NSDictionary *dic in dataArray) {
        if ([[SEGUtils ValueToString:dic[@"parIssueCategoryId"]] isEqualToString:@"-1"]) {
            [rootArray addObject:dic];
        }
    }
    return rootArray;
}

/**
 获取子节点数组
 @param categoryId 父节点ID
 @param dataArray 数据源数组
 */
- (NSArray *)getChildArrayWithId:(NSString *)categoryId dataArray:(NSArray *)dataArray {
    NSMutableArray *childArray = [NSMutableArray array];
    for (NSDictionary *dic in dataArray) {
        if ([[SEGUtils ValueToString:dic[@"parIssueCategoryId"]] isEqualToString:[SEGUtils ValueToString:categoryId]]) {
            [childArray addObject:dic];
        }
    }
    return childArray;
}


/**
 查找根节点
 */
-(NSDictionary *)getRootSelectDic:(NSString *)parIssueCategoryId {
    NSDictionary *dict = nil;
    for (NSDictionary *dic in _dataArray) {
        if ([[SEGUtils ValueToString:parIssueCategoryId] isEqualToString:[SEGUtils ValueToString:dic[@"issueCategoryId"]]]) {
            if ([[SEGUtils ValueToString:dic[@"parIssueCategoryId"]] isEqualToString:@"-1"]) {
                return dic;
            } else {
                return  [self getRootSelectDic:dic[@"parIssueCategoryId"]];
            }
        }
    }
    return dict;
}

/**
 查找父节点
 */
-(NSDictionary *)getFatherSelectDic:(NSString *)parIssueCategoryId {
    NSDictionary *dict = nil;
    for (NSDictionary *dic in _dataArray) {
        if ([[SEGUtils ValueToString:parIssueCategoryId] isEqualToString:[SEGUtils ValueToString:dic[@"issueCategoryId"]]]) {
            dict = dic;
            break;
        }
    }
    return dict;
}


/**
 用于判断数据是否有选择过
 */
- (NSDictionary *)readSelectedStatus {
    NSDictionary *selectedDic = nil;
    for (NSDictionary *dic in _dataArray) {
        if ([dic[@"status"] isEqualToString:@"1"]) {
            selectedDic = dic;
            break;
        }
    }
    return selectedDic;
}

/**
 获取选中的值
 */
- (NSDictionary *)getSelectedCategoryDic {
    NSDictionary *selectedDic = nil;
    for (NSDictionary *dic in _dataArray) {
        if ([dic[@"sel"] isEqualToString:@"1"]) {
            selectedDic = dic;
            break;
        }
    }
    return selectedDic;
}

/**
 选择确认,代理回调
 */
- (void)onBtnFinishedAction:(UIButton *)sender {
    
    NSDictionary *selectedDic = [self getSelectedCategoryDic];
    [self.fundelegate returnSelectedData:selectedDic dataArray:_dataArray];
    [self.navigationController popViewControllerAnimated:YES];
}

/**
 设置源数据
 */
- (void)setDataArray:(NSArray *)dataArray {
    _dataArray = dataArray;
}

#pragma mark - LayOut
/**
 更新UI
 */
- (void)seg_updateViewConstraints {
    
    [lineView2 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.bottom.equalTo(tableView2);
        make.left.equalTo(tableView1.mas_right);
        make.width.mas_equalTo(0.5);
    }];
    
    if (leafArr.count > 0) {
        [tableView1 mas_remakeConstraints:^(MASConstraintMaker *make) {
            make.left.top.equalTo(self.view);
            make.bottom.equalTo(self.view.mas_bottom).offset(-44-LYSafeAreaBottom());
            make.width.equalTo(self.view).dividedBy(3);
        }];
        [tableView2 mas_remakeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(self.view);
            make.bottom.equalTo(self.view.mas_bottom).offset(-44-LYSafeAreaBottom());
            make.left.equalTo(tableView1.mas_right);
            make.width.equalTo(self.view).dividedBy(3);
            
        }];
        [tableView3 mas_remakeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(self.view);
            make.bottom.equalTo(self.view.mas_bottom).offset(-44-LYSafeAreaBottom());
            make.left.equalTo(tableView2.mas_right);
            make.width.equalTo(self.view).dividedBy(3);
        }];
        [lineView2 mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.bottom.equalTo(tableView2);
            make.left.equalTo(tableView1.mas_right);
            make.width.mas_equalTo(0.5);
        }];
        
        [lineView3 mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.bottom.equalTo((self.view));
            make.left.equalTo(tableView2.mas_right);
            make.width.mas_equalTo(0.5);
        }];
    } else {
        [tableView1 mas_remakeConstraints:^(MASConstraintMaker *make) {
            make.left.top.equalTo(self.view);
            make.bottom.equalTo(self.view.mas_bottom).offset(-44-LYSafeAreaBottom());
            make.width.equalTo(self.view).dividedBy(2);
            
        }];
        [tableView2 mas_remakeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(self.view);
            make.bottom.equalTo(self.view.mas_bottom).offset(-44-LYSafeAreaBottom());
            make.left.equalTo(tableView1.mas_right);
            make.width.equalTo(self.view).dividedBy(2);
            
        }];
        [tableView3 removeConstraints:tableView3.constraints];
        [lineView3 removeConstraints:lineView3.constraints];
    }
}

#pragma mark - UI控件

- (UITableView *)newTableViewWithFrame:(CGRect)frame {
    UITableView *tableView = [[UITableView alloc] initWithFrame:frame style:UITableViewStylePlain];
    [tableView setSeparatorStyle:UITableViewCellSeparatorStyleNone];
    [tableView setDelegate:self];
    [tableView setDataSource:self];
    [tableView setBackgroundColor:kColor_W];
    [tableView registerClass:[ProblemClassCell class] forCellReuseIdentifier:kCellIdentifier];
    tableView.tableFooterView = [[UIView alloc] init];
    return tableView;
}

- (UIView *)newLine {
    UIView *lineView = [[UIView alloc] init];
    lineView.backgroundColor = kColor_L2;
    return lineView;
}

- (void)newSubmitButton {
    CustomButtonView* submit = [[CustomButtonView alloc] init];
    [submit setBackgroundImage:[UIImage imageWithColor:kColor_T] forState:UIControlStateNormal];
    [submit setBackgroundImage:[UIImage imageWithColor:kColor_T] forState:UIControlStateHighlighted];
    [submit setTitle:@"确定" forState:UIControlStateNormal];
    [submit addTarget:self action:@selector(onBtnFinishedAction:) forControlEvents:UIControlEventTouchUpInside];
    submit.titleLabel.font = kFont_16;
    submit.contentEdgeInsets = UIEdgeInsetsMake(0, 0, LYSafeAreaBottom(), 0);
    [self.view addSubview:submit];
    
    [submit mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.equalTo(self.view);
        make.bottom.equalTo(self.view);
        make.height.mas_equalTo(44 + LYSafeAreaBottom());
    }];
}
@end
